package dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;

import util.HibernateUtil;
import model.ObjBase;

public class BaseDAO<T extends ObjBase> {
    private Session session;
    @SuppressWarnings("unchecked")
    private Class c;

    @SuppressWarnings("unchecked")
    public BaseDAO(){
        c = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    public void save(ObjBase obj) throws Exception{		
        try {
            setSession(null);
            getSession().beginTransaction();
            if(obj.getId() != null)
            {
                    getSession().merge(obj);
            }else
            {
                    getSession().save(obj);
            }
            getSession().getTransaction().commit();
            getSession().close();
        } catch (ConstraintViolationException e) {
            getSession().beginTransaction().rollback();
            throw new Exception(e.getCause());
        }

    }

    public void update(ObjBase obj) throws Exception {		
        try {
            setSession(null);
            getSession().beginTransaction();
            if(obj.getId() > 0){
                    getSession().merge(obj);
            }else{
                    getSession().update(obj);
            }
            getSession().getTransaction().commit();
            getSession().close();
        } catch (ConstraintViolationException e) {
            getSession().beginTransaction().rollback();
            throw new Exception(e.getCause());
        }
    }

    public void remove(ObjBase obj) throws Exception{
        try {
            getSession().beginTransaction();
            Object obj2 = getSession().load(c, obj.getId());
            getSession().delete(obj2);
            getSession().getTransaction().commit();
            getSession().close();
        } catch (ConstraintViolationException e) {
            getSession().beginTransaction().rollback();
            throw new Exception(e.getCause());
        }
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Session getSession() {
        if(session==null)
        {
            setSession(HibernateUtil.getSessionFactory().openSession());
        }
        if(!session.isOpen())
        {
            setSession(HibernateUtil.getSessionFactory().openSession());
        }
        return session;
    }
    @SuppressWarnings("unchecked")
    public List<T> getList() throws Exception{
        try {
            List<T> li = getSession().createCriteria(c).list();
            getSession().close();
            return li;
        } catch (ConstraintViolationException e) {
            getSession().beginTransaction().rollback();
            throw new Exception(e.getCause());
        }

    }
}